package com.boot.dog.web.aop;

import com.boot.dog.common.annotation.SysLog;
import com.boot.dog.common.util.CommonUtil;
import com.boot.dog.entities.pojo.Log;
import com.boot.dog.common.auth.DogUser;
import com.boot.dog.common.util.SecurityUtil;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.ApplicationContext;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: MaxLv
 * @Date: 2019/12/2
 */
@Aspect
@Component
@RequiredArgsConstructor
public class SysLogAspect {

    private static final ThreadLocal<Long> BEGIN_TIME_THREAD_LOCAL = new NamedThreadLocal<>("ThreadLocal beginTime");

    private static final ThreadLocal<Log> LOG_THREAD_LOCAL = new NamedThreadLocal<>("ThreadLocal log");

    private final ApplicationContext applicationContext;

    private final HttpServletRequest request;

    @Pointcut("@annotation(com.boot.dog.common.annotation.SysLog)")
    public void restAspect() {

    }

    @Before("restAspect()&&@annotation(sysLog)")
    public void before(SysLog sysLog) {
        BEGIN_TIME_THREAD_LOCAL.set(System.currentTimeMillis());
        DogUser user = SecurityUtil.getUser();
        Log log = new Log();
        log.setTitle(sysLog.desc());
        log.setLogType(sysLog.type().ordinal());
        log.setRequestUrl(request.getRequestURI());
        log.setRequestType(request.getMethod());
        log.setOperator(user.getUsername());
        log.setIp(CommonUtil.getIpAddr(request));
        LOG_THREAD_LOCAL.set(log);
    }

    @After("restAspect()")
    public void after() {
        Log log = LOG_THREAD_LOCAL.get();
        long costTime = System.currentTimeMillis() - BEGIN_TIME_THREAD_LOCAL.get();
        log.setCostTime(costTime);
        applicationContext.publishEvent(new SysLogEvent(log));
    }

}
